import logging
from datetime import datetime

class StatusManager:
    def __init__(self, db_manager):
        self.db_manager = db_manager
        
        # 确保通知记录表存在
        self.db_manager.execute_update(
            """CREATE TABLE IF NOT EXISTS daily_notifications (
                notification_date TEXT PRIMARY KEY,
                sent_time TEXT,
                notification_type TEXT
            )""", 
            ()
        )

    def update_status_history(self, db_name, status, details):
        """更新状态历史记录"""
        try:
            check_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            self.db_manager.execute_update(
                "INSERT INTO status_history (db_name, status, check_time, details) VALUES (?, ?, ?, ?)",
                (db_name, status, check_time, details)
            )
        except Exception as e:
            logging.error(f"更新状态历史失败: {str(e)}")
            raise

    def update_current_status(self, db_name, status, details):
        """更新当前状态"""
        try:
            check_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            self.db_manager.execute_update(
                "INSERT OR REPLACE INTO current_status (db_name, status, last_check_time, details) VALUES (?, ?, ?, ?)",
                (db_name, status, check_time, details)
            )
        except Exception as e:
            logging.error(f"更新当前状态失败: {str(e)}")
            raise

    def check_status_recovery(self, db_name, current_status):
        """检查状态是否恢复"""
        check_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        try:
            result = self.db_manager.execute_query(
                "SELECT status FROM current_status WHERE db_name=? ORDER BY last_check_time DESC LIMIT 1",
                (db_name,)
            )
            
            if result and result[0][0] == 'Failed' and current_status == 'Normal':
                self.db_manager.execute_update(
                     "INSERT INTO status_history (db_name, status, check_time, details) VALUES (?, ?, ?, ?)",
                    (db_name, 'Recovered', check_time, '自动恢复')
                )
                return True
            return False
        except Exception as e:
            logging.error(f"状态恢复检查失败: {str(e)}")
            raise

    def update_instance_status(self, db_name, status, details):
        """统一更新实例状态"""
        try:
            # 检查状态恢复
            self.check_status_recovery(db_name, status)
            
            # 更新状态记录
            self.update_current_status(db_name, status, details)
            self.update_status_history(db_name, status, details)
            
            return True
        except Exception as e:
            logging.error(f"更新实例状态失败: {str(e)}")
            return False

    def check_daily_notification_sent(self):
        """检查今天是否已发送过每日通知"""
        try:
            today = datetime.now().strftime('%Y-%m-%d')
            result = self.db_manager.execute_query(
                "SELECT sent_time FROM daily_notifications WHERE notification_date = ?",
                (today,)
            )
            return bool(result)
        except Exception as e:
            logging.error(f"检查每日通知状态失败: {str(e)}")
            return False
            
    def record_daily_notification(self, notification_type="daily_report"):
        """记录每日通知已发送"""
        try:
            today = datetime.now().strftime('%Y-%m-%d')
            now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            self.db_manager.execute_update(
                "INSERT OR REPLACE INTO daily_notifications (notification_date, sent_time, notification_type) VALUES (?, ?, ?)",
                (today, now, notification_type)
            )
            return True
        except Exception as e:
            logging.error(f"记录每日通知状态失败: {str(e)}")
            return False
            